//
//  HomeViewController.swift
//  clreader
//
//  Created by colin on 2019/2/26.
//  Copyright © 2019 colin. All rights reserved.
//

import UIKit
import MJRefresh
import Kingfisher

/// 首页列表
class HomeViewController: CLBaseViewController {

    private lazy var infoTableView = UITableView(frame: CGRect.zero, style: .grouped)
    
    private var dataSource:JSONObject? // 列表数据
    
    private var bannerCellHandle:BannerCell?
    private var ebookCellHandle:EBookCell?
    private var newBookCellHandle:NewBookCell?
    
    private var subjectCellHeight:CGFloat = 0
    
    private var recommandPage = 0 //猜你喜欢页数
    private let recommandPageSize = 3
    private var recommandTaskHandle:URLSessionTask?
    
    enum SectionType:String {
        case 轮播图,菜单,新书速递,类别,精讲,有声书,电子书,视频,专题推荐,猜你喜欢,广告上,广告下
        var key:String {
            switch self {
            case .轮播图:return "banner"
            case .新书速递: return "new_book"
            case .类别:return "subject"
            case .精讲: return "jingjiang"
            case .有声书: return "audio"
            case .电子书: return "book"
            case .视频: return "video"
            case .专题推荐: return "zhuanti"
            case .猜你喜欢: return "recommend"
            case .广告上: return "advtop"
            case .广告下: return "advdown"
            default: return ""
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        
        // 头部
        let header = HeaderView(searchHandle: { [weak self] in
            
            let controller = SearchViewController()
            controller.hidesBottomBarWhenPushed = true
            self?.show(controller, sender: nil)
            
        }) {
            // 扫码
            print("扫码")
        }
        self.view.addSubview(header)
        header.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top)
        }
        
        // 列表
        self.initTableView()
    }

}

extension HomeViewController {
    
    private func initTableView() {
        
        // 注册cell
        self.infoTableView.do {
            $0.register(BannerCell.self, forCellReuseIdentifier: BannerCell.reuseId)
            $0.register(MenuCell.self, forCellReuseIdentifier: MenuCell.reuseId)
            $0.register(SubjectCell.self, forCellReuseIdentifier: SubjectCell.reuseId)
            $0.register(NewBookCell.self, forCellReuseIdentifier: NewBookCell.reuseId)
            $0.register(BookCell.self, forCellReuseIdentifier: BookCell.reuseId)
            $0.register(EBookCell.self, forCellReuseIdentifier: EBookCell.reuseId)
            $0.register(AdCell.self, forCellReuseIdentifier: AdCell.reuseId)
        }
        
        self.infoTableView.do {
            $0.dataSource = self
            $0.delegate = self
        }
        
        self.infoTableView.do {
            $0.contentInsetAdjustmentBehavior = .never
            $0.backgroundColor = UIColor.white
            $0.separatorStyle = .none
            $0.estimatedRowHeight = 0
            $0.estimatedSectionHeaderHeight = 0
            $0.estimatedSectionFooterHeight = 0
            $0.sectionHeaderHeight = 0
            $0.sectionFooterHeight = 0
            $0.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: CGFloat.leastNormalMagnitude))
            $0.contentInset = UIEdgeInsets(top: 44.0, left: 0, bottom: 0, right: 0)
        }
        
        self.view.insertSubview(self.infoTableView, at: 0)
        self.infoTableView.snp.makeConstraints { (make) in
            make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom)
        }
        
        // 下拉刷新
        self.infoTableView.do {
            $0.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
                self?.refresh()
            })
            $0.mj_header?.beginRefreshing()
        }
        
    }
    
    // 全部刷新
    private func refresh() {
        _ = Router.goods.request { [weak self] (response:RequestResponse<JSONObject>) in
            
            self?.infoTableView.mj_header?.endRefreshing()
            
            if case .success(let data,_) = response {
                
                self?.dataSource = data
                self?.ebookCellHandle = nil
                
                self?.infoTableView.reloadData()
                
                self?.refreshBanner()
                // self?.refreshSubject()
                
                self?.recommandTaskHandle?.cancel()
                self?.recommandTaskHandle = nil
                self?.refreshRecommand()
            }
            
            if case .failure(_,let msg) = response {
                self?.hud.showText(msg)
            }
            
        }
        
    }
    
    // 刷新 轮播图
    private func refreshBanner() {
        _ = Router.banner.request { [weak self] (response:RequestResponse<JSONObject>) in
            if case .success(let data,_) = response {
                
                self?.dataSource?[SectionType.轮播图.key] = data?["banner"] as? [JSONObject]
                self?.dataSource?[SectionType.广告上.key] = data?["top"] as? [JSONObject]
                self?.dataSource?[SectionType.广告下.key] = data?["down"] as? [JSONObject]
                
                self?.bannerCellHandle = nil
                self?.infoTableView.reloadData()
                
            }
        }
    }
    
    // 刷新类别
    private func refreshSubject() {
        _ = Router.subject.request { [weak self] (response:RequestResponse<[JSONObject]>) in
            if case .success(let data,_) = response {
                self?.dataSource?[SectionType.类别.key] = data
                self?.infoTableView.reloadData()
            }
        }
    }
    
    // 刷新 猜你喜欢
    private func refreshRecommand() {
        
        if self.recommandTaskHandle != nil {
            return
        }
        
        self.recommandTaskHandle = Router.recommend(pageNum: self.recommandPage, pageSize: self.recommandPageSize, type: nil).request { [weak self] (response:RequestResponse<JSONObject>) in
            
            self?.recommandTaskHandle = nil
            
            if case .success(let data,_) = response {
                if let recommands = data?["rows"] as? [JSONObject],!recommands.isEmpty,
                    let total = data?["total"] as? Int {
                    self?.dataSource?[SectionType.猜你喜欢.key] = data?["rows"] as? [JSONObject]
                    self?.infoTableView.reloadData()
                    
                    guard let `self` = self else { return }
                    if (self.recommandPage + 1) * self.recommandPageSize >= total ||
                        recommands.count < self.recommandPageSize {
                        self.recommandPage = 0
                    } else {
                        self.recommandPage += 1
                    }
                } else {
                    self?.recommandPage = 0
                }
            }
            
            if case .failure(_,let message) = response {
                self?.hud.showText(message)
            }
        }
    }
    
}

extension HomeViewController {
    
    // 轮播图点击
    private func bannerTap(advInfo:JSONObject?) {
        if let sourceType = SourceType(type: advInfo?["type"] as? Int),
            let goods_id = advInfo?["goods_id"] as? Int {
            self.jumpTo(sourceType: sourceType, goods_id: goods_id)
        }
    }
    
    // 菜单点击跳转
    private func menuTap(action:MenuCell.MenuItem) {
        switch action {
        case .精讲:
            let controller = SourceListViewController(sourceType: .精讲)
            controller.hidesBottomBarWhenPushed = true
            self.show(controller, sender: nil)
        case .有声书:
            let controller = SourceListViewController(sourceType: .有声书)
            controller.hidesBottomBarWhenPushed = true
            self.show(controller, sender: nil)
        case .电子书:
            let controller = EBookListViewController()
            controller.hidesBottomBarWhenPushed = true
            self.show(controller, sender: nil)
        case .视频:
            let controller = SourceListViewController(sourceType: .视频)
            controller.hidesBottomBarWhenPushed = true
            self.show(controller, sender: nil)
        case .分类:
            let controller = ClassifyViewController()
            controller.hidesBottomBarWhenPushed = true
            self.show(controller, sender: nil)
        }
    }
    
    @objc private func actionMore(_ sender:Any) {
        if let handle = sender as? UIView {
            let type = self.typeFor(section: handle.tag)
            switch type {
            case .新书速递:
                let controller = EBookListViewController(book_type: 2)
                controller.hidesBottomBarWhenPushed = true
                self.show(controller, sender: nil)
            case .电子书:
                let controller = EBookListViewController()
                controller.hidesBottomBarWhenPushed = true
                self.show(controller, sender: nil)
            case .精讲:
                let controller = SourceListViewController(sourceType: .精讲)
                controller.hidesBottomBarWhenPushed = true
                self.show(controller, sender: nil)
            case .有声书:
                let controller = SourceListViewController(sourceType: .有声书)
                controller.hidesBottomBarWhenPushed = true
                self.show(controller, sender: nil)
            case .视频:
                let controller = SourceListViewController(sourceType: .视频)
                controller.hidesBottomBarWhenPushed = true
                self.show(controller, sender: nil)
            case .专题推荐:
                let controller = SourceListViewController(sourceType: .专题)
                controller.hidesBottomBarWhenPushed = true
                self.show(controller, sender: nil)
            case .猜你喜欢:
                self.refreshRecommand()
            default: break
            }
        }

    }
    
    // 统一跳转
    private func jumpTo(sourceType:SourceType,goods_id:Int) {
        switch sourceType {
        case .电子书:
            let controller = EBookDetailViewController(goods_id: goods_id)
            controller.hidesBottomBarWhenPushed = true
            self.show(controller, sender: nil)
        case .图文, .音频, .视频, .精讲, .专题, .有声书:
            let controller = SourceDetailViewController(sourceType: sourceType, goods_id: goods_id)
            controller.hidesBottomBarWhenPushed = true
            self.show(controller, sender: nil)
        }
    }
    
}

// MARK: - UITableViewDataSource
extension HomeViewController: UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 11
    }
    
    private func typeFor(section:Int) -> SectionType {
        switch section {
        case 0: return .轮播图
        case 1: return .菜单
        case 2: return .新书速递
        case 3: return .精讲
        case 4: return .有声书
        case 5: return .广告上
        case 6: return .电子书
        case 7: return .视频
        case 8: return .广告下
        case 9: return .专题推荐
        case 10: return .猜你喜欢
        default: return .精讲
        }
    }
    
    private func dataFor(type:SectionType) -> [JSONObject] {
        switch type {
        case .轮播图, .类别, .新书速递, .精讲, .有声书, .电子书, .视频, .专题推荐, .猜你喜欢, .广告上, .广告下:
            if let datas = self.dataSource?[type.key] as? [JSONObject] {
                return datas
            } else {
                return []
            }
        default:
            return []
        }
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let type = self.typeFor(section: section)
        let datas = self.dataFor(type: type)
        
        switch type {
        case .轮播图, .类别, .新书速递, .电子书:
            if !datas.isEmpty { return 1 } else { return 0 }
        case .广告上, .广告下:
            if !datas.isEmpty {
                if let enabled = datas[0]["enabled"] as? Int, enabled == 1 {
                    return 1
                }
            }
            return 0
        case .菜单:
            if let data = self.dataSource,!data.isEmpty { return 1 } else { return 0 }
        default:
            return datas.count
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let type = self.typeFor(section: indexPath.section)
        let datas = self.dataFor(type: type)
        
        if type == .轮播图 {
            if let cell = self.bannerCellHandle {
                return cell
            } else {
                let cell = tableView.dequeueReusableCell(withIdentifier: BannerCell.reuseId) as! BannerCell
                cell.refresh(adDatas: datas)
                cell.adClickAction = { [weak self] (adInfo) in
                    self?.bannerTap(advInfo: adInfo)
                }
                self.bannerCellHandle = cell
                return cell
            }
        } else if type == .菜单 {
            let cell = tableView.dequeueReusableCell(withIdentifier: MenuCell.reuseId) as! MenuCell
            cell.itemHandle = { [weak self] (action) in
                self?.menuTap(action: action)
            }
            return cell
        } else if type == .类别 {
            let cell = tableView.dequeueReusableCell(withIdentifier: SubjectCell.reuseId) as! SubjectCell
            cell.refresh(data: datas)
            cell.itemHandle = { [weak self] (item) in
                if let goods_id = item?["goods_id"] as? Int {
                    self?.jumpTo(sourceType: .专题, goods_id: goods_id)
                }
            }
            self.subjectCellHeight = cell.cellHeight // 保存高度
            return cell
        } else if type == .新书速递 {
            if let cell = self.newBookCellHandle {
                return cell
            } else {
                let cell = tableView.dequeueReusableCell(withIdentifier: NewBookCell.reuseId) as! NewBookCell
                cell.refresh(datas)
                cell.selectedHandle = { [weak self] (item) in
                    if let sourceType = SourceType(type: item?["type"] as? Int),
                        let goods_id = item?["goods_id"] as? Int {
                        self?.jumpTo(sourceType: sourceType, goods_id: goods_id)
                    }
                }
                self.newBookCellHandle = cell
                return cell
            }
        } else if type == .广告上 {
            let cell = tableView.dequeueReusableCell(withIdentifier: AdCell.reuseId) as! AdCell
            cell.refresh(datas: datas)
            return cell
        } else if type == .广告下 {
            let cell = tableView.dequeueReusableCell(withIdentifier: AdCell.reuseId) as! AdCell
            cell.refresh(datas: datas)
            return cell
        } else if type == .电子书 {
            if let cell = self.ebookCellHandle {
                return cell
            } else {
                let cell = tableView.dequeueReusableCell(withIdentifier: EBookCell.reuseId) as! EBookCell
                cell.refresh(datas)
                cell.selectedHandle = { [weak self] (goods) in
                    if let goods_id = goods?["goods_id"] as? Int, goods_id > 0 {
                        self?.jumpTo(sourceType: .电子书, goods_id: goods_id)
                    }
                }
                self.ebookCellHandle = cell
                return cell
            }
        } else if type == .猜你喜欢 {
            let cell = tableView.dequeueReusableCell(withIdentifier: BookCell.reuseId) as! BookCell
            cell.refresh(data: datas[indexPath.row],isShowSourceType: true)
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: BookCell.reuseId) as! BookCell
            cell.refresh(data: datas[indexPath.row])
            return cell
        }
    }
}

// MARK: - UITableViewDelegate
extension HomeViewController: UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let type = self.typeFor(section: section)
        
        switch type {
        case .新书速递, .精讲, .有声书, .电子书, .视频, .专题推荐, .猜你喜欢:
            let datas = self.dataFor(type: type)
            if !datas.isEmpty {
                let headerView = UIView().then {
                    let tagView = UIView()
                    tagView.backgroundColor = UIColor(hex: "AE1600")
                    $0.addSubview(tagView)
                    tagView.snp.makeConstraints({ (make) in
                        make.left.equalToSuperview().offset(15.0)
                        make.size.equalTo(CGSize(width: 3.0, height: 20.0))
                        make.centerY.equalToSuperview()
                    })
                    
                    let labelTitle = UILabel().then {
                        $0.textColor = UIColor(hex: "343434")
                        $0.font = UIFont.systemFont(ofSize: 22.0, weight: .bold)
                        $0.text = type.rawValue
                    }
                    $0.addSubview(labelTitle)
                    labelTitle.snp.makeConstraints({ (make) in
                        make.left.equalTo(tagView.snp.right).offset(5.0)
                        make.centerY.equalToSuperview()
                    })
                    
                    // 按钮 todo
                    let buttonMore = UIButton(type: .custom).then {
                        if type == .猜你喜欢 {
                            $0.setImage(UIImage(named: "ic_home_change"), for: .normal)
                            $0.setTitle("  换一换", for: .normal)
                        } else {
                            $0.setTitle("查看全部", for: .normal)
                        }
                        $0.setTitleColor(UIColor(hex: "AE1600"), for: .normal)
                        $0.titleLabel?.font = UIFont.systemFont(ofSize: 13.0, weight: .bold)
                        $0.tag = section
                        $0.addTarget(self, action: #selector(self.actionMore(_:)), for: .touchUpInside)
                    }
                    $0.addSubview(buttonMore)
                    buttonMore.snp.makeConstraints({ (make) in
                        make.top.bottom.equalToSuperview()
                        make.right.equalToSuperview().offset(-15.0)
                    })
                    
                }
                return headerView
            } else {
                return nil
            }
        default:
            return nil
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        let type = self.typeFor(section: section)
        switch type {
        case .新书速递, .精讲, .有声书, .电子书, .视频, .专题推荐, .猜你喜欢:
            let datas = self.dataFor(type: type)
            if !datas.isEmpty {
                return 40.0
            } else {
                return CGFloat.leastNormalMagnitude
            }
        default:
            return CGFloat.leastNormalMagnitude
        }
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        let type = self.typeFor(section: section)
        switch type {
        case .精讲, .有声书, .电子书, .视频, .专题推荐, .猜你喜欢:
            let datas = self.dataFor(type: type)
            if !datas.isEmpty {
                return 20.0
            } else {
                return CGFloat.leastNormalMagnitude
            }
        default:
            return CGFloat.leastNormalMagnitude
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let type = self.typeFor(section: indexPath.section)
        switch type {
        case .轮播图:
            return BannerCell.bannerSize.height
        case .菜单:
            return MenuCell.height
        case .类别:
            return self.subjectCellHeight
        case .新书速递:
            return NewBookCell.cellHeight
        case .广告上, .广告下:
            return AdCell.height
        case .电子书:
            return EBookCell.cellHeight
        default:
            return BookCell.height
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let type = self.typeFor(section: indexPath.section)
        let datas = self.dataFor(type: type)
        switch type {
        case .精讲, .有声书, .视频, .专题推荐, .猜你喜欢, .广告上, .广告下:
            let data = datas[indexPath.row]
            if let sourceType = SourceType(type: data["type"] as? Int),
                let goods_id = data["goods_id"] as? Int {
                self.jumpTo(sourceType: sourceType, goods_id: goods_id)
            }
        default:break
        }        
    }
}
